package zeke.com.camera.activity;

import java.io.IOException;

import zeke.com.R;
import zeke.com.camera.control.CameraManager;
import zeke.com.camera.picture.PictureCallBack;
import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.hardware.Camera;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;

public class CamareActivity extends Activity implements SurfaceHolder.Callback {
	
	private SurfaceView surfaceView = null;
	private SurfaceHolder surfaceHolder = null;
	private Button takePicture = null;
	private Camera camera = null;
	
	private LinearLayout warm_view = null;
	
	private boolean isStartPreview = false;
	
	//-----------重力感应---------------
	private SensorManager sensorManager = null;
	private Sensor acceSensor = null;
	private Handler handler = null;
	private Double a,c,acos;
	//-----------重力感应---------------
	
	private SensorEventListener mySensorEventListener = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		initFrame();
		
		initSensor();
		
		setContentView(zeke.com.R.layout.capture);

		FrameLayout captrueFrameLayout = (FrameLayout) this.findViewById(R.id.captrueFrameLayout);
		ViewGroup.LayoutParams captrueFrameLayoutParams = captrueFrameLayout.getLayoutParams();

		CameraManager.init(getApplication(), captrueFrameLayoutParams.width,captrueFrameLayoutParams.height);
		
		warm_view = (LinearLayout) findViewById(R.id.warm_view);
		
		takePicture = (Button) findViewById(R.id.takePicture);

		takePicture.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				PictureCallBack back = new PictureCallBack(camera.getParameters().getPreviewSize());
				camera.takePicture(null, null, back);
				
				
			}
		});


	}
	
	//-------重力感应----------
	private void initSensor(){
		sensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
        acceSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        
        handler = new Handler(Looper.myLooper()){
        	public void handleMessage(android.os.Message msg) {
        		SensorEvent event = (SensorEvent) msg.obj;
//        		x.setText("event.values[x]:"+event.values[0]);
//    			y.setText("event.values[y]:"+event.values[1]);
//    			z.setText("event.values[z]:"+event.values[2]);
    			a = Double.valueOf(event.values[0]);
    			c = Double.valueOf(event.values[1]);
    			acos = Math.acos(Math.abs(a)/Math.sqrt((Math.pow(a, 2)+Math.pow(c, 2))));
    			
    			if(acos<0.8d){
    				takePicture.setEnabled(true);
    				warm_view.setVisibility(View.GONE);
    			}else{
    				takePicture.setEnabled(false);
    				warm_view.setVisibility(View.VISIBLE);
    			}
    			
        	};
        };
        
        mySensorEventListener = new MySensorEventListener(handler);
	}
	//-------重力感应----------
	class MySensorEventListener implements SensorEventListener{
    	private Message msg = null;
    	private Handler handler = null;
    	public MySensorEventListener(Handler handler){
    		this.handler = handler;
    	}
		public void onSensorChanged(SensorEvent event) {
			msg = handler.obtainMessage();
			msg.obj = event;
			handler.sendMessage(msg);
		}
		public void onAccuracyChanged(Sensor sensor, int accuracy) { }
    }

	private void initFrame() {
		Window window = getWindow();
		window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

		window.requestFeature(Window.FEATURE_NO_TITLE);
		window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
	}

	@Override
	protected void onResume() {
		super.onResume();
		//-------重力感应----------
		//currently we create one Handler instance per listener, but we could have one per looper
    	//针对多个传感器相互协作的时候使用
    	sensorManager.registerListener(mySensorEventListener, acceSensor, SensorManager.SENSOR_DELAY_NORMAL, handler);

    	//-------------------
		surfaceView = (SurfaceView) findViewById(R.id.preview_view);
		surfaceHolder = surfaceView.getHolder();

		surfaceHolder.addCallback(this);
		surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
	}
	
	 @Override
    protected void onPause() {
    	// TODO Auto-generated method stub
    	super.onPause();
    	//-------重力感应----------
    	sensorManager.unregisterListener(mySensorEventListener, acceSensor);
    }
	    

	public void surfaceCreated(SurfaceHolder holder) {
		initCamera(holder);
		camera = CameraManager.get().getCamera();
		
		if(!isStartPreview){
			isStartPreview = true;
			CameraManager.get().startPreview();
		}
	}

	public void surfaceDestroyed(SurfaceHolder holder) {
		CameraManager.get().stopPreview();
		CameraManager.get().closeDriver();
		isStartPreview = false;
	}

	public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
		initCamera(holder);
		camera = CameraManager.get().getCamera();
		if(!isStartPreview){
			isStartPreview = true;
			CameraManager.get().startPreview();
		}
	}

	private void initCamera(SurfaceHolder surfaceHolder) {
		try {
			CameraManager.get().openDriver(surfaceHolder);
		} catch (IOException ioe) {
			Log.w("xxxx", ioe);
			return;
		} catch (RuntimeException e) {
			// Barcode Scanner has seen crashes in the wild of this variety:
			// java.?lang.?RuntimeException: Fail to connect to camera service
			Log.w("xxx", "Unexpected error initializating camera", e);
			return;
		}
	}

}
